import { styled } from '@umijs/max'
import { Button, Col, Form, Input, Modal, Row, Select, Space, Table } from 'antd'
import { useEffect, useState } from 'react'
import { useRequest } from 'ahooks'
import { PAGINATION_CONFIG } from '@/constants'
import type { ColumnsType } from 'antd/es/table'
import type { Station, QueryStationListParams } from '@/pages/station/stationList/services'
import { queryStationList, StationStatus } from '@/pages/station/stationList/services'
import { enum2options } from '@/utils/enum2options'
import { Access } from '@umijs/max'
import { CloseCircleFilled } from '@ant-design/icons'

const ModalContent = styled.div`
  display: flex;
  flex-direction: column;
  gap: 20px;

  .ant-form-item {
    margin: 0;
  }
`

export interface StationSelected {
  id: string
  name: string
}

interface StationSelectProps {
  value?: StationSelected[]
  onChange?: (value?: StationSelected[]) => void
  style?: React.CSSProperties
  disabled?: boolean
  type?: 'radio' | 'checkbox'
  allowClear?: boolean
  inline?: boolean
  fromType?: number
}

interface SelectModalProps {
  fromType?: number
  initValue?: StationSelected[]
  open?: boolean
  onClose?: () => void
  onSelect?: (value?: StationSelected[]) => void
  type: 'radio' | 'checkbox'
}

type Selected = {
  [key: number]: StationSelected[]
}

const SelectModal: React.FC<SelectModalProps> = props => {
  const [searchForm] = Form.useForm<QueryStationListParams>()
  const [searchParams, setSearchParams] = useState<QueryStationListParams>({
    pageNum: 1, pageSize: 10, fromType: props.fromType,
  });
  const userList = useRequest(() => queryStationList(searchParams), {
    ready: props.open,
    refreshDeps: [searchParams],
  })
  const [selected, setSelected] = useState<Selected>({});

  const columns: ColumnsType<Station> = [
    {
      title: '场站名称',
      dataIndex: 'stationName',
    },
    {
      title: '场站地址',
      dataIndex: 'address',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: val => StationStatus[val],
    },
  ]

  const onFinish = (formValues: QueryStationListParams) => {
    setSearchParams({
      ...searchParams,
      ...formValues,
      pageNum: 1,
    })
  }

  const onReset = () => {
    searchForm.resetFields()
  }

  const onCancel = () => {
    props.onClose?.()
  }

  const onOk = () => {
    let result: StationSelected[] = []
    Object.values(selected).forEach((val: StationSelected[]) => result = result.concat(val))
    props.onSelect?.(result)
    onCancel()
  }

  useEffect(() => {
    if (props.open && props.initValue) {
      setSelected({1: props.initValue})
    } else {
      setSelected({})
    }
  }, [props.open]);

  return (
    <Modal
      open={props.open}
      width={800}
      title='选择场站'
      onOk={onOk}
      onCancel={onCancel}
    >
      <ModalContent>
        <Form form={searchForm} onFinish={onFinish} onReset={onReset}>
          <Row gutter={[20, 20]}>
            <Col span={8}>
              <Form.Item label='场站名称' name='title'>
                <Input placeholder='请输入' />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label='状态' name='status'>
                <Select placeholder='请选择' options={enum2options(StationStatus)} allowClear />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Space>
                <Button type='primary' htmlType='submit' loading={userList.loading}>筛选</Button>
                <Button onClick={onReset}>重置</Button>
              </Space>
            </Col>
          </Row>
        </Form>
        <Table<Station>
          rowKey='id'
          loading={userList.loading}
          dataSource={userList.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: userList.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
          rowSelection={{
            type: props.type,
            selectedRowKeys: selected[searchParams.pageNum]?.map(it => it.id),
            onChange: (_, rows) => {
              setSelected({
                ...selected,
                [searchParams.pageNum]: rows.map(it => ({id: it.id, name: it.stationName}))
              })
            }
          }}
        />
      </ModalContent>
    </Modal>
  )
}

const StationSelect: React.FC<StationSelectProps> = props => {
  const [open, setOpen] = useState(false)

  const close = () => {
    setOpen(false)
  }

  const allowClear = () => {
    props.onChange?.(undefined)
  }
  
  return <div style={props.style}>
    {
      props.type === 'checkbox' 
      ? <a onClick={() => setOpen(true)}>选择场站</a>
      : <div style={{display: 'flex', gap: 8, alignItems: 'center'}}>
        <Input
          placeholder='请选择'
          value={props.value?.[0]?.name}
          disabled={props.disabled}
          readOnly
          addonAfter={props.disabled ? '选择' : <a onClick={() => setOpen(true)}>选择</a>}
          suffix={!!props.allowClear && !!props.inline && !!props.value?.length ? <CloseCircleFilled onClick={allowClear} style={{color: '#ccc'}} /> : undefined}
        />
        <Access accessible={!!props.allowClear && !props.inline}>
          <a onClick={allowClear} style={{flexShrink: 0}}>清除</a>
        </Access>
      </div>
    }
    <SelectModal
      open={open}
      onClose={close}
      initValue={props.value}
      onSelect={props.onChange}
      fromType={props.fromType}
      type={props.type || 'radio'}
    />
  </div>
}

export default StationSelect
